<template>
  <div>
    <!-- 面包屑导航区 -->
    <bread-nav>
      <span slot="c1">商品管理</span>
      <span slot="c2">参数列表</span>
    </bread-nav>

    <!-- 卡片视图区 -->
    <el-card>
      <!-- 警告区 -->
      <el-alert
        title="警告：只允许为第三级分类设置相关参数！"
        type="warning"
        :closable="false"
        show-icon
      ></el-alert>

      <!-- 选择商品分类区 -->
      <el-row class="row-top">
        <el-col>
          <span>选择商品分类：</span>
          <!-- 级联选择框 -->
          <el-cascader
            v-model="selectKeys"
            :options="allGoodsCate"
            expandTrigger="hover"
            :props="cascaderProps"
            @change="handleChange"
          ></el-cascader>
        </el-col>
      </el-row>

      <!-- tap 页签区 -->
      <el-tabs v-model="activeName" @tab-click="handleTabClick">
        <el-tab-pane label="动态参数" name="many">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addParams"
            >添加属性</el-button
          >
          <!-- 动态参数表格 -->
          <el-table :data="manyData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  class="tag"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i, scope.row)"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible & inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column type="index"></el-table-column>
            <!-- 内容 -->
            <el-table-column
              label="参数名称"
              prop="attr_name"
            ></el-table-column>
            <!-- 按钮 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="showDeleteDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
        <el-tab-pane label="静态参数" name="only">
          <el-button
            type="primary"
            size="mini"
            :disabled="isBtnDisable"
            @click="addParams"
            >添加参数</el-button
          >
          <!-- 静态参数表格 -->
          <el-table :data="onlyData" border stripe>
            <!-- 展开行 -->
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-tag
                  class="tag"
                  v-for="(item, i) in scope.row.attr_vals"
                  closable
                  @close="handleClose(i, scope.row)"
                  :key="i"
                  >{{ item }}</el-tag
                >
                <el-input
                  class="input-new-tag"
                  v-if="scope.row.inputVisible & inputVisible"
                  v-model="inputValue"
                  ref="saveTagInput"
                  size="small"
                  @keyup.enter.native="handleInputConfirm(scope.row)"
                  @blur="handleInputConfirm(scope.row)"
                >
                </el-input>
                <el-button
                  v-else
                  class="button-new-tag"
                  size="small"
                  @click="showInput(scope.row)"
                  >+ New Tag</el-button
                >
              </template>
            </el-table-column>
            <!-- 索引 -->
            <el-table-column type="index"></el-table-column>
            <!-- 内容 -->
            <el-table-column
              label="属性名称"
              prop="attr_name"
            ></el-table-column>
            <!-- 按钮 -->
            <el-table-column label="操作">
              <template slot-scope="scope">
                <el-button
                  type="primary"
                  size="mini"
                  icon="el-icon-edit"
                  @click="showEditDialog(scope.row.attr_id)"
                  >编辑</el-button
                >
                <el-button
                  type="danger"
                  size="mini"
                  icon="el-icon-delete"
                  @click="showDeleteDialog(scope.row.attr_id)"
                  >删除</el-button
                >
              </template>
            </el-table-column>
          </el-table>
        </el-tab-pane>
      </el-tabs>
    </el-card>

    <!-- 添加参数区 -->
    <el-dialog
      :title="'添加' + paramsTitle"
      :visible.sync="addParamsVisible"
      width="50%"
      @close="addParamsClose"
    >
      <!-- 添加参数对话框 -->
      <el-form
        ref="addFormRef"
        :rules="addFormRules"
        :model="addForm"
        label-width="100px"
      >
        <el-form-item :label="paramsTitle" prop="attr_name">
          <el-input v-model="addForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="addParamsInfo">确 定</el-button>
      </span>
    </el-dialog>

    <!-- 修改参数区 -->
    <el-dialog
      :title="'修改' + paramsTitle"
      :visible.sync="editParamsVisible"
      width="50%"
      @close="editParamsClose"
    >
      <!-- 修改参数对话框 -->
      <el-form
        ref="editFormRef"
        :rules="editFormRules"
        :model="editForm"
        label-width="100px"
      >
        <el-form-item :label="paramsTitle" prop="attr_name">
          <el-input v-model="editForm.attr_name"></el-input>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="editParamsVisible = false">取 消</el-button>
        <el-button type="primary" @click="editParamsInfo">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import BreadNav from 'components/content/nav/BreadNav.vue'
import { cateCel } from 'network/goods.js'
export default {
  name: 'Params',
  components: { BreadNav },
  data() {
    return {
      allGoodsCate: [],
      // 级联选择框配置对象
      cascaderProps: {
        value: 'cat_id',
        label: 'cat_name',
        children: 'children',
      },
      // 级联选择框双向绑定数组
      selectKeys: [],
      // 被激活的页签的名称
      activeName: 'many',
      // 动态参数数据
      manyData: [],
      // 静态参数数据
      onlyData: [],
      // 添加参数框变量
      addParamsVisible: false,
      // 添加参数表单数据
      addForm: {},
      // 添加表单验证规则对象
      addFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      // 修改参数框变量
      editParamsVisible: false,
      // 修改表单验证规则
      editFormRules: {
        attr_name: [
          { required: true, message: '请输入参数名称', trigger: 'blur' },
        ],
      },
      // 输入框的显示
      inputVisible: false,
      // 输入框中的值
      inputValue: '',
      // 修改表单的数据
      editForm: {},
    }
  },
  created() {
    this.getAllGoodsCate()
  },
  computed: {
    isBtnDisable() {
      if (this.selectKeys.length !== 3) {
        return true
      }
      return false
    },
    cateId() {
      if (this.selectKeys.length === 3) {
        return this.selectKeys[2]
      }
      return null
    },
    // 添加参数标题
    paramsTitle() {
      if (this.activeName === 'many') {
        return '属性'
      }
      return '参数'
    },
  },
  methods: {
    async getAllGoodsCate() {
      const { data: res } = await this.$http.get('categories')

      if (res.meta.status !== 200) {
        return this.$message.error('获取分类列表失败！')
      }
      this.allGoodsCate = res.data
    },
    // 级联选择框变化触发函数
    handleChange() {
      if (this.selectKeys.length !== 3) {
        // 清空级联选择框
        this.selectKeys = []
        // 清空动态参数
        this.manyData = []
        // 清空静态参数
        this.onlyData = []
        return
      }

      // 根据所选分类的 id 和当前所处的面板请求数据
      this.getCurrentCateData()
    },
    // 获取参数数据
    async getCurrentCateData() {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes`,
        {
          params: {
            sel: this.activeName,
          },
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数列表失败，请先选择商品分类！')
      }
      if (this.activeName === 'many') {
        this.manyData = res.data
      } else {
        this.onlyData = res.data
      }
      res.data.forEach((item) => {
        // 三元表达式判断 attr_vals 的值是否为空
        item.attr_vals = item.attr_vals ? item.attr_vals.split(' ') : []
        // 为每一个标签绑定单独的 值 和 布尔值
        item.inputVisible = false
        item.inputValue = ''
      })
    },
    // tab 页签点击事件函数
    handleTabClick() {
      this.getCurrentCateData()
    },
    // 添加参数按钮
    addParams() {
      this.addParamsVisible = true
    },
    // 重置添加参数表单
    addParamsClose() {
      this.$refs.addFormRef.resetFields()
    },
    // 添加参数方法
    async putParams() {
      const { data: res } = await this.$http.post(
        `categories/${this.cateId}/attributes`,
        {
          attr_name: this.addForm.attr_name,
          attr_sel: this.activeName,
        }
      )
      if (res.meta.status !== 201) {
        return this.$message.error('添加参数失败！')
      }
      this.getCurrentCateData()
      this.addParamsVisible = false
      this.$message.success('添加参数成功！')
    },
    // 添加参数框确认按钮
    addParamsInfo() {
      this.$refs.addFormRef.validate((valid) => {
        if (!valid) return

        this.putParams()
      })
    },
    // 重置修改表单方法
    editParamsClose() {
      this.$editFormRef.resetFields()
    },
    // 根据 id 获取修改数据
    async getEditData(id) {
      const { data: res } = await this.$http.get(
        `categories/${this.cateId}/attributes/${id}`,
        {
          params: {
            attr_sel: this.activeName,
          },
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('获取参数失败！')
      }
      this.editForm = res.data
    },
    // 修改按钮
    showEditDialog(id) {
      this.getEditData(id)
      this.editParamsVisible = true
    },
    // 上传修改的参数
    async putEditParams() {
      const { data: res } = await this.$http.put(
        `categories/${this.cateId}/attributes/${this.editForm.attr_id}`,
        {
          attr_name: this.editForm,
          attr_sel: this.activeName,
        }
      )

      if (res.meta.status !== 200) {
        return this.$message.error('修改参数失败！')
      }
      this.getCurrentCateData()
      this.editParamsVisible = false
      this.$message.success('修改参数成功！')
    },
    // 修改表单框确认按钮
    editParamsInfo() {
      this.$refs.editFormRef.validate((valid) => {
        if (!valid) return
      })

      this.putEditParams()
    },
    // 重置编辑表单方法
    editParamsClose() {
      this.$refs.editFormRef.resetFields()
    },
    // 删除按钮
    async showDeleteDialog(id) {
      const resultConfirm = await this.$confirm(
        '此操作将永久删除该参数, 是否继续?',
        '提示',
        {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning',
        }
      ).catch(() => {
        return this.$message.info('取消删除！')
      })

      if (resultConfirm === 'confirm') {
        const { data: res } = await this.$http.delete(
          `categories/${this.cateId}/attributes/${id}`
        )
        if (res.meta.status !== 200) {
          return this.$message.error('删除参数失败！')
        }
        this.getCurrentCateData()
        this.$message.success('删除参数成功！')
      }
    },
    // 添加标签文本框按下enter件或者获取焦点触发方法
    handleInputConfirm(scope) {
      scope.inputVisible = false
      this.inputVisible = false
      // trim() 的作用是去除字符串两端的字符串
      if (this.inputValue.trim().length === 0) {
        this.inputValue = ''
        return
      }
      // 输入的内容为合法内容，处理数据修改操作
      scope.attr_vals.push(this.inputValue)
      this.inputValue = ''
      // 发起请求保存参数
      this.saveAttrval(scope)
    },
    // 保存参数函数
    async saveAttrval(scope) {
      const newAttr_vals = scope.attr_vals.join(' ')
      const obj = {
        attr_name: scope.attr_name,
        attr_sel: scope.attr_sel,
        attr_vals: newAttr_vals,
      }
      const { data: res } = await cateCel(scope.cat_id, scope.attr_id, obj)
      if (res.meta.status !== 200) {
        this.$message.error('修改参数失败！')
        return
      }
      this.$message.success('修改参数成功！')
    },
    // 点击按钮展示添加标签文本输入框
    showInput(scope) {
      // this.$set(scope, 'inputVisible', true)
      // console.log(scope.inputVisible)
      // this.$forceUpdate()
      scope.inputVisible = true
      this.inputVisible = true
      // $nextTick 的作用： 当页面中的元素重新渲染的时候执行里面的元素
      this.$nextTick((_) => {
        this.$refs.saveTagInput.$refs.input.focus()
      })
    },
    // 删除参数事件
    handleClose(i, scope) {
      scope.attr_vals.splice(i, 1)
      this.saveAttrval(scope)
    },
  },
}
</script>

<style scoped>
.row-top {
  margin-top: 15px;
}
.input-new-tag {
  width: 150px !important;
}
.tag {
  margin-right: 15px !important;
}
.tag:nth-child(1) {
  margin-left: 15px !important;
}
</style>